package com.xiaoran.springcloud.controller;

import com.xiaoran.springcloud.entitis.CommonResult;
import com.xiaoran.springcloud.entitis.Payment;
import com.xiaoran.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
public class PaymentController {
    @Autowired
    private PaymentService paymentService;
    @Value("${server.port}")
    private String serverport;
    @Autowired
    private DiscoveryClient discoveryClient;

    @PostMapping("/payment/create")
    public CommonResult  create(@RequestBody Payment payment){
        int result=paymentService.create(payment);
        log.info("插入的结果是：{}xx",result);
        if(result>0){
            return new CommonResult(200,"插入数据库成功 .serverport:"+serverport,200);
        }else{
            return new CommonResult(404,"插入数据库失败",null);
        }
    }
    @GetMapping("/payment/get/{id}")
    public CommonResult  getPaymentById(@PathVariable("id")int id){
        Payment payment=paymentService.getPaymentById(id);
        log.info("插入的结果是：{}",payment);
        if(payment!=null){
            return new CommonResult(200,"查询成功:serverport:"+serverport,payment);
        }else{
            return new CommonResult(404,"查询失败，没有这个ID"+id,null);
        }
    }

    @GetMapping("/payment/discovery")
    public DiscoveryClient discoveryClient(){
       List<String> list= discoveryClient.getServices();
       for(String name:list){
           log.info(name);
       }
       List<ServiceInstance> list1=discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
       for (ServiceInstance name1:list1){
           log.info(name1.getServiceId()+"\t"+name1.getHost()+"\t"+ name1.getPort()+"\t"+name1.getUri());
       }
        return this.discoveryClient;
    }

    @GetMapping("/payment/lb")
    public String getPaymentlb(){
        return serverport;
    }

    @GetMapping("/payment/fegin/timeout")
    public String test2(){
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return serverport;
    }

    @GetMapping("/payment/zipkin")
    public String paymentZipkin(){
        return "hi,i am paymentZipkin server final ,welcome come to china HhhhHhh";
    }
}
